<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\response\Json;
class Recommand extends BaseController
{

    /**
     * Get paginated user list with filters
     */
    public function index()
    {
        try {
            $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }

        $token = $matches[1];
        $currentUser = Db::name('think_users')->where('token', $token)->find();
        if (!$currentUser) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        $currentUserNumber = $currentUser['user_number'];
            // Get query parameters
            $page = (int)Request::param('page', 1);
            $pageSize = (int)Request::param('size', 10);
            $gender = Request::param('gender');
            $isVerified = Request::param('isVerified');
            $isVip = Request::param('isVip');
            $keyword = Request::param('keyword');
            $online = Request::param('online');
            $cid = Request::param('cid');
            
            // Build base query
            $query = Db::name('think_users')
                      ->where('status', 1) // Only active users
                      ->where('user_number', '<>', $currentUserNumber); // 排除当前用户

            // Apply filters
            if ($gender !== null) {
                $query->where('gender', $gender);
            }
            
            if ($isVerified !== null) {
                $query->where('is_verified', $isVerified);
            }
            
            if ($online !== null) {
                $query->where('online', $online);
            }

            // VIP status filter
            if ($isVip !== null) {
                if ($isVip) {
                    $query->where('vip_expire_date', '>', date('Y-m-d H:i:s'));
                } else {
                    $query->where(function ($q) {
                        $q->whereNull('vip_expire_date')
                          ->whereOr('vip_expire_date', '<=', date('Y-m-d H:i:s'));
                    });
                }
            }

            // Keyword search
            if ($keyword) {
                $query->where(function ($q) use ($keyword) {
                $q->whereOr([
                    ['nickname', 'like', "%{$keyword}%"],
                    ['location', 'like', "%{$keyword}%"]  // 搜索整个 location JSON
                    ]);
                });
            }

            // Get total count
            $total = $query->count();

            // Get paginated data
            $list = $query->page($page, $pageSize)
             ->field([
                 'id',
                 'nickname as name',  // rename nickname to name
                 'avatar as poster',  // rename avatar to poster
                 'location',
                 'bio as announce',
                 'is_verified as realPeople',  // rename is_verified to realPeople
                 'tags as labels',
                 'score',
                 'online',
                 'last_active_time'
             ])
             ->order('online', 'desc')
             ->order('score', 'desc')
             ->select()
             ->each(function ($item) {
                 // Process labels
                 $item['labels'] = $item['labels'] ? 
                        json_decode($item['labels'], true) : [];
        
                // Process location
                $location = json_decode($item['location'], true);
                $item['address'] = $location['address'] ?? '';  // 提取 address
                unset($item['location']);  // 移除原始 location 字段
                return $item;
             });
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'list' => $list,
                    'pagination' => [
                        'total' => $total,
                        'page' => $page,
                        'pageSize' => $pageSize,
                        'totalPages' => ceil($total / $pageSize)
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    public function categorys() {
        try {
        $categories = [
            [
                'id' => 0,
                'title' => 'All users'
            ],
            [
                'id' => 1,
                'title' => 'Spotlight'
            ],
            [
                'id' => 2,
                'title' => 'New'
            ],
            [
                'id' => 3,
                'title' => 'Nearby'
            ]
        ];

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $categories
        ]);

    } catch (\Exception $e) {
        return json([
            'code' => 500,
            'msg' => $e->getMessage()
        ]);
    }
    }

    /**
     * 获取用户详情
     * @return Json
     */
    public function detail(): Json
    {
        // 验证Bearer Token
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
    
        $token = $matches[1];
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => 'token无效']);
        }
        // 获取目标用户ID
        $targetUserId = (int)Request::param('id');
        if (!$targetUserId) {
            return json(['code' => 400, 'msg' => '用户ID不能为空', "data"=>Request::param()]);
        }
        $currentUserId = $user['id'];
        $beenBlocked = Db::name('think_blacklist')
            ->where('user_id', $targetUserId)
            ->where('blocked_user_id', $currentUserId)
            ->find();
        if ($beenBlocked) {
            return json(['code' => 403, 'msg' => '您已被拉黑']);
        }

        $isBlocked = Db::name('think_blacklist')
            ->where('user_id', $currentUserId)
            ->where('blocked_user_id', $targetUserId)
            ->find();

        // 查询用户基本信息
        $user = Db::name('think_users')
            ->where('id', $targetUserId)
            ->where('status', 1)
            ->field([
                'id',
                'nickname',
                'avatar',
                'gender',
                'birthday',
                'location',
                'bio',
                'score',
                'vip_level',
                'is_verified',
                'verified_time',
                'vip_expire_date',
                'online',
                'height',
                'weight',
                'order_count',
                'message_price',
                'audio_price',
                'video_price',
                'tags',
                'last_active_time'
            ])
            ->find();

        if (!$user) {
            return json(['code' => 404, 'msg' => '用户不存在或已被禁用']);
        }

        // 计算用户年龄
        $age = null;
        if ($user['birthday']) {
            $birthday = new \DateTime($user['birthday']);
            $today = new \DateTime();
            $age = $birthday->diff($today)->y;
        }

        // 查询用户媒体列表
        $mediaList = Db::name('user_media_records')
            ->where('user_id', $targetUserId)
            ->where('media_type', 'IMAGE')
            ->where('status', 1)
            ->field([
                'media_url',
                "width",
                "height",
                "media_type"
            ])
            ->order('create_time', 'desc')
            ->select()
            ->toArray();

        // 处理标签数据
        $user['tags'] = $user['tags'] ? json_decode($user['tags'], true) : [];

        // 组装返回数据
        $data = [
            'user_info' => [
                'id' => $user['id'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
                'gender' => (int)$user['gender'],
                'age' => $age,
                'location' => json_decode($user['location'], true),
                'bio' => $user['bio'],
                'score' => (float)$user['score'],
                'vip_level' => (int)$user['vip_level'],
                'is_verified' => (bool)$user['is_verified'],
                'verified_time' => $user['verified_time'],
                'vip_expire_date' => $user['vip_expire_date'],
                'is_online' => (bool)$user['online'],
                'height' => (int)$user['height'],
                'weight' => (int)$user['weight'],
                'order_count' => (int)$user['order_count'],
                'chat_prices' => [
                    'message' => (int)$user['message_price'],
                    'audio' => (int)$user['audio_price'],
                    'video' => (int)$user['video_price']
                ],
                'tags' => $user['tags'],
                'last_active_time' => $user['last_active_time'],
                'is_blocked' => !empty($isBlocked) // 添加黑名单状态
            ],
            'media_list' => $mediaList
        ];

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $data
        ]);
    }
}